package com.company.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.eduservice.entity.EduCourse;
import com.company.eduservice.entity.EduCourseDescription;
import com.company.eduservice.entity.EduTeacher;
import com.company.eduservice.entity.EduVideo;
import com.company.eduservice.feign.VideoFeignService;
import com.company.eduservice.mapper.EduCourseMapper;
import com.company.eduservice.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.eduservice.vo.course.CourseInfoVo;
import com.company.eduservice.vo.course.CourseNotarizeVo;
import com.company.eduservice.vo.front.CourseFrontVo;
import com.company.eduservice.vo.front.CourseWebVo;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-04-18
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {

    @Resource
    private EduCourseDescriptionService descriptionService;

    @Resource
    private EduTeacherService teacherService;

    @Resource
    private EduSubjectService subjectService;

    @Resource
    private EduVideoService videoService;

    @Resource
    private EduChapterService chapterService;

    @Resource
    private VideoFeignService videoFeignService;

    @Override
    @Transactional
    public String saveCourseInfo(CourseInfoVo vo) {
        //添加课程的基本信息
        EduCourse eduCourse = new EduCourse();
        eduCourse.setIsDeleted(0);
        BeanUtils.copyProperties(vo, eduCourse);
        this.baseMapper.insert(eduCourse);

        //添加课程的描述信息
        EduCourseDescription eduCourseDescription = new EduCourseDescription();
        eduCourseDescription.setDescription(vo.getDescription());
        eduCourseDescription.setId(eduCourse.getId());
        descriptionService.save(eduCourseDescription);

        return eduCourse.getId();
    }

    //确认课程信息
    @Override
    @Transactional
    public CourseNotarizeVo courseNotarizeById(String id) {
        CourseNotarizeVo vo = new CourseNotarizeVo();

        EduCourse eduCourse = this.getById(id);
        vo.setId(eduCourse.getId());
        vo.setTitle(eduCourse.getTitle());
        vo.setPrice(eduCourse.getPrice());
        vo.setLessonNum(eduCourse.getLessonNum());
        vo.setCover(eduCourse.getCover());

        String name = teacherService.getById(eduCourse.getTeacherId()).getName();
        vo.setTeacherName(name);

        String title1 = subjectService.getById(eduCourse.getSubjectParentId()).getTitle();
        String title2 = subjectService.getById(eduCourse.getSubjectId()).getTitle();
        vo.setSubjectLevelOne(title1);
        vo.setSubjectLevelTwo(title2);
        return vo;
    }

    //删除课程
    @Override
    @Transactional
    public void deleteCourseById(String courseId) {
        List<EduVideo> videos = videoService.list(new QueryWrapper<EduVideo>().eq("course_id", courseId));
        if (videos != null && videos.size() > 0) {
            List<String> list = new ArrayList<>();
            videos.forEach((v) -> {
                if (!StringUtils.isEmpty(v.getVideoSourceId())) {
                    list.add(v.getVideoSourceId());
                }
            });
            if (list.size() > 0) {
                videoFeignService.deleteBatch(list);
            }
        }

        videoService.deleteVedioByCourseId(courseId);
        chapterService.deleteChapterByCourseId(courseId);
        descriptionService.removeById(courseId);
        this.removeById(courseId);
    }

    //查询前8条热门课程
    @Override
    @Cacheable(key = "'selectIndexList'", value = "course")
    public List<EduCourse> getCourseList() {
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("buy_count");
        wrapper.last("limit 8");
        List<EduCourse> list = this.list(wrapper);
        return list;
    }

    @Override
    public List<EduCourse> getCourseByTeacherId(String teacherId) {
        List<EduCourse> list = this.list(new QueryWrapper<EduCourse>().eq("teacher_id", teacherId));
        return list;
    }

    @Override
    public Map<String, Object> pageTeacherList(Page<EduCourse> page, CourseFrontVo frontVo) {
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        String subjectParentId = frontVo.getSubjectParentId();  //一级分类
        String subjectId = frontVo.getSubjectId();  //二级分类
        String buyCountSort = frontVo.getBuyCountSort();  //销量排序
        String gmtCreateSort = frontVo.getGmtCreateSort();  //时间排序
        String priceSort = frontVo.getPriceSort();  //价格排序

        if (!StringUtils.isEmpty(subjectParentId)){
            wrapper.eq("subject_parent_id", subjectParentId);
        }

        if (!StringUtils.isEmpty(subjectId)){
            wrapper.eq("subject_id", subjectId);
        }

        if (!StringUtils.isEmpty(buyCountSort)){
            wrapper.orderByDesc("buy_count");
        }

        if (!StringUtils.isEmpty(gmtCreateSort)){
            wrapper.orderByDesc("gmt_create");
        }

        if (!StringUtils.isEmpty(priceSort)){
            wrapper.orderByDesc("price");
        }

        this.baseMapper.selectPage(page, wrapper);

        List<EduCourse> records = page.getRecords();
        long current = page.getCurrent();
        long pages = page.getPages();
        long size = page.getSize();
        long total = page.getTotal();
        boolean hasNext = page.hasNext();//下一页
        boolean hasPrevious = page.hasPrevious();//上一页

        Map<String, Object> map = new HashMap<>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        return map;
    }

    @Override
    public CourseWebVo getFrontCourseInfo(String courseId) {
        EduCourse course = this.getById(courseId);
        String teacherId = course.getTeacherId();
        EduTeacher teacher = teacherService.getById(teacherId);
        EduCourseDescription description = descriptionService.getById(courseId);
        String title1 = subjectService.getById(course.getSubjectParentId()).getTitle();
        String title2 = subjectService.getById(course.getSubjectId()).getTitle();

        CourseWebVo vo = new CourseWebVo();
        BeanUtils.copyProperties(course, vo);
        vo.setDescription(description.getDescription());
        vo.setTeacherName(teacher.getName());
        vo.setTeacherId(teacherId);
        vo.setIntro(teacher.getIntro());
        vo.setAvatar(teacher.getAvatar());
        vo.setSubjectLevelOneId(course.getSubjectParentId());
        vo.setSubjectLevelOne(title1);
        vo.setSubjectLevelTwoId(course.getSubjectId());
        vo.setSubjectLevelTwo(title2);
        return vo;
    }

    @Override
    public Integer getCourseViewCount() {
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        wrapper.select("view_count");
        List<EduCourse> list = this.list(wrapper);
        Integer count = null;
        for (EduCourse course : list) {
            int value = course.getViewCount().intValue();
            count += value;
        }
        return count;
    }
}
